<?php
declare (strict_types = 1);
namespace app\common\model\content;

use app\admin\traits\GetTableData;
use think\Exception;
use think\Model;
use app\common\model\user\User;

class Category extends Model
{
    use GetTableData;



    // 设置字段信息
    protected $schema = [
        'id'            => 'int',
        'name'          => 'string',
        'desc'          => 'string',
        'user_id'       => 'int',
        'create_time'   => 'int',
        'update_time'   => 'int',
    ];

    // 类型转换
    protected $type = [
        'id'            => 'integer',
        'user_id'       => 'integer',
    ];


    //插入之前完善数据
    public static function onBeforeInsert(Model $model)
    {
        $model->setAttr('user_id',app()->user->getId());
    }

    //删除之前判断是否存在文章
    public static function onBeforeDelete(Model $model)
    {
        if ( $model->hasArticle($model->id) ){
            throw new Exception('请先删除分类下的文章');
        }
        //删除之前要删除包含的话题
        return Topic::destroy(function($query) use ($model){
            $query->where('category_id','=',$model->id);
        });
    }


    /**
     * 检测是否包含内容(文章 话题)
     * @param int $id 分类id
     * @return bool
     */
    public function hasArticle(int $id){
        return (bool) Article::where(['category_id'=>$id])->count();
    }


    //关联用户
    public function user()
    {
        return $this->belongsTo(User::class,'user_id', 'id')->bind([
            'username' => 'showName',
            'avatar' => 'avatarUrl'
        ]);
    }
    //关联话题
    public function topics()
    {
        return $this->hasMany(Topic::class);
    }
    //关联文章
    public function articles()
    {
        return $this->hasMany(Article::class);
    }

    //获取分类列表table数据
    public static function getListData(array $ruleWhere = []){
        //要查询的字段
        $fields = [
            'fields' =>['id','name','desc','user_id','create_time','update_time'],
            'with' => ['user'],
            'withCount' => ['articles'],
        ];

        //(构建查询条件)
        $where = [];
        if (input('start_time')){
            $where[] = ['create_time', '>=', strtotime(input('start_time'))];
        }
        if (input('end_time')){
            $where[] = ['create_time', '<=', strtotime( input('end_time'))];
        }
        if (input('name')){
            $where[] = ['name','like','%'.input('name').'%'];
        }

        //排序
        $order = ['id'=>'desc','create_time'=>'desc'];

        //[count:查询到的数目, list:记录列表]
        $data = static::operateDatum($where, $fields, $order,$ruleWhere);

        return [
            'count' => $data['count'],
            'data' => $data['list']
        ];
    }

    //获取下拉列表数据
    public static function getDropList(string $oreder = 'DESC'){
        return static::order(['id'=>$oreder, 'create_time'=>$oreder])->column('name','id');
    }


}